//
//  LCHomeStatusesViewModel.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/5.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import SDWebImage
//为主页服务的ViewModel
class LCHomeStatusesViewModel: NSObject {
    
    //定义一个全局的数据源数组
    var modelList:[LCHomeCellViewModel] = [LCHomeCellViewModel]()
    
    //加载首页的数据
    func loadStatuses(isUp:Bool,callBack:@escaping (Bool,String) ->()){
        var maxId:Int64 = 0
        var sinceId:Int64 = 0
        if isUp {
            maxId = modelList.last?.statusess?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else{
            sinceId = modelList.first?.statusess?.id ?? 0
            
        }
        
        var count = "没有最新的数据加载"
        LCNetMansagerTools.sharedTools.requestHomeStatuses(maxId:maxId,sinceId:sinceId) {(responds, error) in
            if error != nil{
                
                callBack(false,count)
                return
            }
            //代码到此处是请求没有出现错误的
            //字典转模型
            let dic:[String:Any] = responds as! [String:Any]
            let statusesArray = dic["statuses"] as! [[String:Any]]
            var modelArray = [LCHomeStatusesModel]()
            
            //MARK:第二种方式使用YYModel来完成字典转模型
            modelArray = NSArray.yy_modelArray(with: LCHomeStatusesModel.self, json: statusesArray) as! [LCHomeStatusesModel]
            
            //MARK:第一种遍历数据使用KVC构造函数来完成字典转模型
            //            for dict in statusesArray{
            //                let model = LCHomeStatusesModel(dicte: dict)
            //                modelArray .append(model)
            //            }
            
            //MARK:将demol数组转换成viewmodel数组
            var viewModelArray = [LCHomeCellViewModel]()
            
            //创建调度组
            let imageGroup = DispatchGroup.init()
            
            for model in modelArray{
                //在这里判断原创和转发是否是单张图片
                if model.pic_urls?.count == 1{
                    if let imageUrl = model.pic_urls?.first?.thumbnail_pic{
                        
                        //添加调度组
                        imageGroup.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: imageUrl), options: [], progress: nil, completed: { (image, error, _, _, _) in
                            print("原创单张图片下载完成")
                            //图片下载完成移除调度组
                            imageGroup.leave()
                        })
                        
                    }
                    
                }
                if model.retweeted_status?.pic_urls?.count == 1{
                    if let imageUrl = model.retweeted_status?.pic_urls?.first?.thumbnail_pic{
                        
                        //添加调度组
                        imageGroup.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string:imageUrl), options: [], progress: nil, completed: { (image, error, _, _, _) in
                            print("转发单张图片下载完成")
                            //图片下载完成移除调度组
                            imageGroup.leave()
                        })
                    }
                    
                }
                
                
                let viewModel = LCHomeCellViewModel()
                viewModel.statusess = model
                viewModelArray.append(viewModel)
            }
       
            if isUp{
                 //如果是上啦加载
                self.modelList.append(contentsOf: viewModelArray)
            }else{
                //如果是下拉刷新
                self.modelList.insert(contentsOf: viewModelArray, at: 0)
            }
            //调度组中任务全部执行完成后,再去回调闭包来刷新UI界面
            imageGroup.notify(queue: DispatchQueue.main, execute: { 
                //tableview刷新数据
                if viewModelArray.count>0{
                count = "有最新的\(viewModelArray.count)条数据加载"
                }
                callBack(true,count)
            })
        
        }
        
    }
}
